package com.cn.wanxi.servlet;

import com.cn.wanxi.dto.ResultModel;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 新增的时候用post方法，查询用get方法
 * 注意：post和get 的区别
 * 1.查询效率的区别
 * 2.传值大小的区别  get比4k较小  post理论上无限制
 * 3.安全性的区别  post高
 */
@WebServlet("/addNews")
public class BackNewsAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.拿到前端的值
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String top = req.getParameter("isTop");
        String tuijian = req.getParameter("isTuijian");
        String news_plate_id = req.getParameter("type");

//        2.将前端的值封装到一个model
        NewsModel newsModel = new NewsModel();
        newsModel.setTitle(title);
        newsModel.setContent(content);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        newsModel.setCreate_time(simpleDateFormat.format(date));
        newsModel.setTop("true".equals(top));//拿到页面是否置顶的值
        newsModel.setTuijian("true".equals(tuijian));//页面拿到推荐的值
        newsModel.setShenhe(false);
        newsModel.setNews_plate_id(news_plate_id == null ? 0 : Integer.parseInt(news_plate_id));
//        3.调用服务层
        INewsService newsService = new NewsServiceImpl();
/**
 * ResultModel返回结果
 * 1.成功或者失败的编码    200成功 400失败
 * 2.成功或者失败的信息   恭喜你，新增成功
 * 3.返回一个结果集  List 查询返回   int新增，修改， 删除
 */
        ResultModel resultModel = newsService.addNews(newsModel);
//        4.返回数据
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        System.out.println(jsonArray.toString());
        resp.getWriter().println(jsonArray);
    }
}
